package com.mybatispluslambda.cglib;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

public class ClassUtil {
    private static final String filePath = "/mapper/FBusInstanceHistoryMapper.xml"; //配置文件路径

    private static Object dynamicClass(Object object) throws Exception {
        HashMap<String, Object> returnMap = new HashMap<>();
        HashMap<String, Class<?>> typeMap = new HashMap<>();
        //读取配置文件
        Properties prop = new Properties();
        InputStream in = ClassUtil.class.getResourceAsStream(filePath);
        prop.load(in);
        Set<String> keyList = prop.stringPropertyNames();
        Class type = object.getClass();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(object);
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    returnMap.put(propertyName, "");
                }
                typeMap.put(propertyName, descriptor.getPropertyType());
            }
        }
        //加载配置文件中的属性
        for (String key : keyList) {
            returnMap.put(key, prop.getProperty(key));
            typeMap.put(key, String.class);
        }
        //map转换成实体对象
        DynamicBean bean = new DynamicBean(typeMap);
        //赋值
        Set<String> keys = typeMap.keySet();
        for (String key : keys) {
            bean.setValue(key, returnMap.get(key));
        }
        return bean.getObject();
    }

    public static void main(String[] args) throws Exception {
        Student stu = new Student();
        System.out.println(stu);
        Object x = dynamicClass(stu);
        System.out.println(x);
    }
}